﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using YoucaiReader.Resources;
using Assistant;
using YoucaiReader.Helper;
using System.Windows.Media;
using YoucaiReader.Entities;
using System.Windows.Media.Imaging;
using System.Net.Sockets;
using System.Threading;

namespace YoucaiReader
{
    public partial class MainPage : PhoneApplicationPage
    {
        YoucaiReader.UserControls.ReaderHelperControl rhc = new UserControls.ReaderHelperControl();
        private BookListModel TodayRecommended_M = new BookListModel();

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            //
            if ((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"] != Visibility.Visible)
            {
                SolidColorBrush solidColorBrush = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
                Application.Current.Resources.Add("PhoneBackgroundBrush", solidColorBrush);
            }
            if (SettingHelper.IsSettings("BookReader_Default"))
            {
                App.ReaderPage_Night = (bool)SettingHelper.GetValueFromSettings("BookReader_NightMode");
            }
            else
            {
                SettingHelper.SaveInToSettings("BookReader_Default", true);
                SettingHelper.SaveInToSettings("BookReader_fontSize", 26);
                SettingHelper.SaveInToSettings("BookReader_BackgroundNum", 0);
                SettingHelper.SaveInToSettings("ReaderPage_Bright", 0.08);
                SettingHelper.SaveInToSettings("ReaderPage_NightBright", 0.5);
                SettingHelper.SaveInToSettings("BookReader_NightMode", false);
                App.ReaderPage_Night = false;
                InternalDefaultBook.AddInternalBook();//App自带书籍
            }
            //
            this.Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            //首次需要显示阅读帮助
            if (!SettingHelper.IsSettings("QQReaderHelp"))
            {
                SettingHelper.SaveInToSettings("QQReaderHelp", true);
                this.rhc.SetPhoneApplicationPage(this, "MainPage");
                this.LayoutRoot.Children.Add(this.rhc);
            }
            else if (this.mainPanorama.SelectedIndex == 0)
            {
                base.ApplicationBar.IsVisible = true;
            }
            //
            if (this.mainPanorama.SelectedIndex == 0)
            {
                //我的书架
                //this.bookListBox1.ItemsSource = App.LocalBook.T_LocalBookList_VM1();
                //this.bookListBox2.ItemsSource = App.LocalBook.T_LocalBookList_VM2();
            }
            //foreach (BookListModel bookListM in App.LocalBook.T_LocalBookList_VM1())
            //{
            //    if (bookListM.str_Id_M != App.ReaderFileName)
            //    {
            //        continue;
            //    }
            //    SaveReaderHistory.Delete(bookListM);
            //    SaveReaderHistory.Save(bookListM);
            //}
            //foreach (BookListModel bookListM1 in App.LocalBook.T_LocalBookList_VM2())
            //{
            //    if (bookListM1.str_Id_M != App.ReaderFileName)
            //    {
            //        continue;
            //    }
            //    SaveReaderHistory.Delete(bookListM1);
            //    SaveReaderHistory.Save(bookListM1);
            //}
            this.SetReaderHistory();

        }


        #region 阅读历史
        private void SetReaderHistory()
        {
            //历史大块标识
            if (!SettingHelper.IsSettings("ReaderHistory1"))
            {
                this.lstItemReaderHistoryBig_CoverNULL.Visibility = Visibility.Visible;
                this.lstItemReaderHistoryBig_Cover.Visibility = System.Windows.Visibility.Collapsed;
                this.lstItemReaderHistoryBig_Title.Text = "暂无记录";
                this.lstItemReaderHistoryBig_Author.Text = string.Empty;
                this.lstItemReaderHistoryBig_Progress.Text = string.Empty;
            }
            else
            {
                BookListModel bookListM = new BookListModel();
                bookListM = SettingHelper.GetValueFromSettings("ReaderHistory1") as BookListModel;
                this.lstItemReaderHistoryBig_CoverNULL.Visibility = Visibility.Collapsed;
                this.lstItemReaderHistoryBig_Cover.Visibility = Visibility.Visible;
                this.lstItemReaderHistoryBig_Cover.Source = new BitmapImage(new Uri(bookListM.str_Cover_M, (InternalDefaultBook.IsInternalBook(bookListM.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
                this.lstItemReaderHistoryBig_Title.Text = bookListM.str_Title_M;
                this.lstItemReaderHistoryBig_Author.Text = bookListM.str_Author_M;
                if (SettingHelper.IsSettings(string.Concat(bookListM.str_Id_M, "CurrentReaderBook")))
                {
                    LocalBookProgressListModel valueFromSettings = SettingHelper.GetValueFromSettings(string.Concat(bookListM.str_Id_M, "CurrentReaderBook")) as LocalBookProgressListModel;
                    this.lstItemReaderHistoryBig_Progress.Text = GetNowTime.SetPercentageText(valueFromSettings.double_ReaderProgress_M);
                }
                //历史小左
                if (!SettingHelper.IsSettings("ReaderHistory2"))
                {
                    this.lstHomeReadHistorySamllLeft_CoverNULL.Visibility = Visibility.Visible;
                    this.lstHomeReadHistorySamllLeft_Cover.Visibility = Visibility.Collapsed;
                    this.lstHomeReadHistorySamllLeft_Grid.Visibility = Visibility.Collapsed;
                    this.lstHomeReadHistorySamllLeft_Title.Text = string.Empty;
                    this.lstHomeReadHistorySamllLeft_Progress.Text = string.Empty;
                    return;
                }
                BookListModel bookListM1 = new BookListModel();
                this.lstHomeReadHistorySamllLeft_Cover.Visibility = Visibility.Visible;
                this.lstHomeReadHistorySamllLeft_Grid.Visibility = Visibility.Visible;
                this.lstHomeReadHistorySamllLeft_CoverNULL.Visibility = Visibility.Collapsed;
                bookListM1 = SettingHelper.GetValueFromSettings("ReaderHistory2") as BookListModel;
                this.lstHomeReadHistorySamllLeft_Cover.Source = new BitmapImage(new Uri(bookListM1.str_Cover_M, (InternalDefaultBook.IsInternalBook(bookListM1.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
                this.lstHomeReadHistorySamllLeft_Title.Text = bookListM1.str_Title_M;
                if (SettingHelper.IsSettings(string.Concat(bookListM1.str_Id_M, "CurrentReaderBook")))
                {
                    LocalBookProgressListModel localBookProgressListM = SettingHelper.GetValueFromSettings(string.Concat(bookListM1.str_Id_M, "CurrentReaderBook")) as LocalBookProgressListModel;
                    this.lstHomeReadHistorySamllLeft_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM.double_ReaderProgress_M);
                }
                //历史小右
                if (!SettingHelper.IsSettings("ReaderHistory3"))
                {
                    this.lstHomeReadHistorySamllRight_CoverNULL.Visibility = Visibility.Visible;
                    this.lstHomeReadHistorySamllRight_Cover.Visibility = Visibility.Collapsed;
                    this.lstHomeReadHistorySamllRight_Grid.Visibility = Visibility.Collapsed;
                    this.lstHomeReadHistorySamllRight_Title.Text = string.Empty;
                    this.lstHomeReadHistorySamllRight_Progress.Text = string.Empty;
                    return;
                }
                BookListModel valueFromSettings1 = new BookListModel();
                this.lstHomeReadHistorySamllRight_Cover.Visibility = Visibility.Visible;
                this.lstHomeReadHistorySamllRight_Grid.Visibility = Visibility.Visible;
                this.lstHomeReadHistorySamllRight_CoverNULL.Visibility = Visibility.Collapsed;
                valueFromSettings1 = SettingHelper.GetValueFromSettings("ReaderHistory3") as BookListModel;
                this.lstHomeReadHistorySamllRight_Cover.Source = new BitmapImage(new Uri(valueFromSettings1.str_Cover_M, (InternalDefaultBook.IsInternalBook(valueFromSettings1.str_Id_M) ? UriKind.Relative : UriKind.RelativeOrAbsolute)));
                this.lstHomeReadHistorySamllRight_Title.Text = valueFromSettings1.str_Title_M;
                if (SettingHelper.IsSettings(string.Concat(valueFromSettings1.str_Id_M, "CurrentReaderBook")))
                {
                    LocalBookProgressListModel localBookProgressListM1 = SettingHelper.GetValueFromSettings(string.Concat(valueFromSettings1.str_Id_M, "CurrentReaderBook")) as LocalBookProgressListModel;
                    this.lstHomeReadHistorySamllRight_Progress.Text = GetNowTime.SetPercentageText(localBookProgressListM1.double_ReaderProgress_M);
                    return;
                }
            }
        }
        #endregion 阅读历史


        /// <summary>
        /// 移除帮助信息
        /// </summary>
        public void RemoveHelp()
        {
            if (this.LayoutRoot.Children.IndexOf(this.rhc) >= 0)
            {
                this.LayoutRoot.Children.Remove(this.rhc);
            }
        }

        private void mainPanorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            base.Focus();
            if (base.ApplicationBar != null)
            {
                if (this.mainPanorama.SelectedIndex != 0)
                {
                    base.ApplicationBar.IsVisible = false;
                    return;
                }
                base.ApplicationBar.IsVisible = true;
            }
        }

        #region ******************************设置关于，反馈建议******************************
        private void ApplicationBarIconButton_Feedback_Click(object sender, EventArgs e)
        {
            NavigateServiceHelper.Navigate(ReaderNavigatePageContants.FeedbackPage);
        }

        private void ApplicationBarIconButton_Settings_Click(object sender, EventArgs e)
        {
            NavigateServiceHelper.Navigate(ReaderNavigatePageContants.AboutPage);
        }
        #endregion ******************************设置关于，反馈建议******************************

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //try
            //{
            //    if (this.menuChanged)
            //    {
            //        this.menuChanged = false;
            //    }
            //    else if (MessageBoxResult.Cancel != MessageBox.Show("确定要退出吗？", string.Empty, MessageBoxButton.OKCancel))
            //    {
            //        this.downloadUpdateTime.Stop();
            //        App.DownloadList.RemoveTemporaryProgress();
            //        this.Exit();
            //    }
            //    else
            //    {
            //        e.Cancel = true;
            //        return;
            //    }
            //}
            //catch (Exception exception)
            //{
            //    e.Cancel = true;
            //}
        }

        #region ListBox的相关事件
        private void lstHomeReadHistory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void lstItemReaderHistoryBig_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            lstHomeReadHistory_Tap("ReaderHistory1");
        }

        private void lstHomeReadHistorySamllLeft_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            lstHomeReadHistory_Tap("ReaderHistory2");
        }

        private void lstHomeReadHistorySamllRight_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            lstHomeReadHistory_Tap("ReaderHistory3");
        }

        void lstHomeReadHistory_Tap(string key)
        {
            if (SettingHelper.IsSettings(key))
            {
                BookListModel bookListM = new BookListModel();
                bookListM = SettingHelper.GetValueFromSettings(key) as BookListModel;
                NavigateServiceHelper.Navigate(ReaderNavigatePageContants.BookReaderPage, string.Concat("?FileName=", bookListM.str_Id_M));
                SaveReaderHistory.Delete(bookListM);
                SaveReaderHistory.Save(bookListM);
                SettingHelper.SaveInToSettings("ReaderPageBack", true);
            }
        }

        private void lstHomeReadToday_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.imgTodayError.Visibility != Visibility.Visible && this.TodayRecommended_M.str_Id_M != "")
            {
                SettingHelper.SaveInToSettings("BookDetail", this.TodayRecommended_M);
                NavigateServiceHelper.Navigate(ReaderNavigatePageContants.BookDetailPage, "");
            }
        }
        #endregion ListBox的相关事件





        
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
           
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
           
            base.OnNavigatedFrom(e);
        }

        public string GetIPAddress()
        {
            string strIPAddress = null;
            List<string> arrayIPAddress = new List<string>();            
            var hostNames = Windows.Networking.Connectivity.NetworkInformation.GetHostNames();
            foreach (var hn in hostNames)
            {
                if (hn.IPInformation != null)
                {
                    string ipAddress = hn.DisplayName;
                    arrayIPAddress.Add(ipAddress);
                }
            }
            if (arrayIPAddress.Count < 1)
            {
                return null;
            }
            if (arrayIPAddress.Count == 1)
            {
                strIPAddress = arrayIPAddress[0];
            }
            if (arrayIPAddress.Count > 1)
            {
                strIPAddress = arrayIPAddress[arrayIPAddress.Count - 1];
            }
            // System.Console.WriteLine();
            for (int i = 0; i < arrayIPAddress.Count; i++)
            {
                System.Diagnostics.Debug.WriteLine("No.{0} host IP is: {1}", i + 1, arrayIPAddress[i]);
            }
            return strIPAddress;
        }
    }
}